/**
 * 代码库空库克隆
 */

import React from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
import { Button, Message, Input, Select } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import track from 'utils/track';
import './emptyClone.scss';
import utils from 'utils';
import exceed from 'utils/apimap';
import { getFeature } from 'utils/features';
import PersonalSettings from 'components/PersonalSettings';
import intl from '../../../../../../../../locale';

const https_notset_repo_ids = 'https-notset-repo-ids';
const ssh_notset_repo_ids = 'ssh-notset-repo-ids';
export default class RepoOverviewInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      keys: null,
    };
  }

  componentDidMount() {
    this.getKeys();
  }

  getKeys = () => {
    exceed
      .forceFetch({
        api: 'keys.list',
        data: {
          page: 1,
          per_page: 10,
        },
      })
      .then((result) => {
        this.setState({
          keys: result.list,
        });
      });
  };

  setCachedRepoIds = (key) => {
    const ids = this.getCachedRepoIds(key);
    const valueItem = this.getCachedRepoValue();
    if (!ids.includes(valueItem)) {
      ids.push(valueItem);
    }
    utils.setCachedData(key, JSON.stringify(ids));
  };

  getCachedRepoValue = () => {
    const { pathResource, user } = window.FORCE;
    return `${pathResource.id}_${user.codeUserId}`;
  };

  getCachedRepoIds = (key) => {
    const curIdStr = utils.getCachedData(key);
    if (curIdStr) {
      return JSON.parse(curIdStr);
    }
    return [];
  };

  render() {
    const { projectInfo } = this.props;
    // 公有云ssh给提示，云效ssh、https都给提示
    const { cloneWay } = this.props;

    const { httpsAccount } = this.props;

    const dataSource = [
      {
        title: 'SSH',
        address: projectInfo.ssh_url_to_repo,
      },

      {
        title: 'HTTPS',
        address: projectInfo.http_url_to_repo,
      },
    ];

    const { keys } = this.state;

    const sshMsgClose = this.getCachedRepoIds(ssh_notset_repo_ids).includes(
      this.getCachedRepoValue(),
    );
    const httpsMsgClose = this.getCachedRepoIds(https_notset_repo_ids).includes(
      this.getCachedRepoValue(),
    );

    return (
      <div className="empty-clone">
        <div className="empty-clone-select-content">
          <Select
            className="gitClone-way-select"
            value={cloneWay}
            onChange={(value) => {
              this.props.updateData({
                cloneWay: value,
              });
            }}
          >
            {dataSource.map((item) => {
              return <Select.Option value={item.title}>{item.title}</Select.Option>;
            })}
          </Select>
          <Input
            className="gitClone-address-input"
            value={dataSource.find((item) => item.title === cloneWay).address}
            readOnly
          />

          <CopyToClipboard
            text={dataSource.find((item) => item.title === cloneWay).address}
            onCopy={() => {
              track({
                action: cloneWay === 'SSH' ? 'copy_ssh' : 'copy_https',
                page: 'Empty-Repo',
                type: '',
                control: '',
              });

              Message.success({
                title: intl.get({
                  id: 'code-assets.containers.repoOverviewInfo.emptyClone.CopiedSuccessfully',
                  defaultMessage: '复制成功',
                }),
              });
            }}
          >
            <Button type="normal" className="gitClone-copy-btn" onClick={() => {}}>
              <YunxiaoIcon type="copy-line" />
            </Button>
          </CopyToClipboard>
        </div>
        <div className="empty-clone-tip">
          {getFeature('personal.settings.httpsPw') && cloneWay === 'HTTPS' && !httpsMsgClose && httpsAccount && (
            <Message
              className="https-clone-message"
              type="notice"
              closeable
              onClose={() => {
                this.setCachedRepoIds(https_notset_repo_ids);
              }}
            >
              {httpsAccount.account_type !== 'no_https_secret' ? (
                <div className="tip-content">
                  <div>
                    {intl.get({
                      id: 'code-assets.containers.repoOverviewInfo.emptyClone.ForgotToCloneAnAccount',
                      defaultMessage: '忘记克隆账号或密码？',
                    })}
                  </div>
                  <div>
                    <PersonalSettings
                      className="clone-message-link"
                      type="httpsPw"
                    >
                      {intl.get({
                        id: 'code-assets.containers.repoOverviewInfo.emptyClone.ViewNow',
                        defaultMessage: '立即查看',
                      })}
                    </PersonalSettings>
                  </div>
                </div>
              ) : (
                <div className="tip-content">
                  <div>
                    {intl.get({
                      id: 'code-assets.containers.repoOverviewInfo.emptyClone.TheHttpsClonePasswordIs',
                      defaultMessage: '未配置 HTTPS 克隆密码，请先设置',
                    })}
                  </div>
                  <div>
                    <PersonalSettings
                      className="clone-message-link"
                      type="httpsPw"
                    >
                      {intl.get({
                        id: 'code-assets.containers.repoOverviewInfo.emptyClone.Configure',
                        defaultMessage: '去设置',
                      })}
                    </PersonalSettings>
                  </div>
                </div>
              )}
            </Message>
          )}

          {cloneWay === 'SSH' && keys && !sshMsgClose && (
            <Message
              className="ssh-notset-message"
              type="notice"
              closeable
              onClose={() => {
                this.setCachedRepoIds(ssh_notset_repo_ids);
              }}
            >
              {keys.length > 0 ? (
                <div className="tip-content">
                  <div>
                    {intl.get({
                      id: 'code-assets.containers.repoOverviewInfo.emptyClone.ManageSshKeys',
                      defaultMessage: '管理 SSH 密钥？',
                    })}
                  </div>
                  <div>
                    <PersonalSettings
                      className="clone-message-link"
                      type="ssh"
                    >
                      {intl.get({
                        id: 'code-assets.containers.repoOverviewInfo.emptyClone.ViewNow',
                        defaultMessage: '立即查看',
                      })}
                    </PersonalSettings>
                  </div>
                </div>
              ) : (
                <div className="tip-content">
                  <div>
                    {intl.get({
                      id: 'code-assets.containers.repoOverviewInfo.emptyClone.TheSshKeyIsNot',
                      defaultMessage: '未配置 SSH 密钥，请先设置',
                    })}
                  </div>
                  <div>
                    <PersonalSettings
                      className="clone-message-link"
                      type="ssh"
                    >
                      {intl.get({
                        id: 'code-assets.containers.repoOverviewInfo.emptyClone.Configure',
                        defaultMessage: '去设置',
                      })}
                    </PersonalSettings>
                  </div>
                </div>
              )}
            </Message>
          )}
        </div>
      </div>
    );
  }
}
